﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Animation;
using System.Windows.Media;
using BlogTruyen.Framework;
using BlogTruyen.Models;
using System.Reflection;

namespace BlogTruyen
{
    public partial class Home : PhoneApplicationPage
    {
        #region SettingPanelProperty
        private double _dragDistanceToOpen = 35.0;
        private double _settingPanelWidth = 400;
        private double _dragDistanceNegative = -35.0;
        private bool _isSettingsOpen = false;
        private int _slideDuration = 300;
        private FrameworkElement _feContainer;
        #endregion

        ViewModels.MainPage ViewModel;
        
        public Home()
        {
            InitializeComponent();
            
            ViewModel = new ViewModels.MainPage();
            DataContext = ViewModel;

            var home = new UserControls.Home();
            Navigate(home, "Home");
            home.StoryTap += home_StoryTap;

            #region SettingPanelInitialize
            SettingsPane.Width = _settingPanelWidth;
            SettingsPane.Margin = new Thickness(-(480 + _settingPanelWidth), 0, 0, 0);
            _feContainer = this.Container as FrameworkElement;
            #endregion

        }

        void home_StoryTap(object sender, EventArgs e)
        {
            var story = ((FrameworkElement)sender).DataContext as Models.Story;
            NavigationService.Navigate(new Uri(string.Format("/StoryDetails.xaml?url={0}&title={1}",story.url,HttpUtility.UrlEncode(story.title)),UriKind.Relative));
        }

        #region SettingPanelParsing

        private void ApplicationBarIconButton_OnClick(object sender, EventArgs e)
        {
            if (_isSettingsOpen)
            {
                CloseSettings();
            }
            else
            {
                OpenSettings();
            }
        }

        private void CloseSettings()
        {
            var trans = _feContainer.GetHorizontalOffset().Transform;
            trans.Animate(trans.X, 0, TranslateTransform.XProperty, _slideDuration, 0, new CubicEase
            {
                EasingMode = EasingMode.EaseOut
            });

            _isSettingsOpen = false;
        }

        private void OpenSettings()
        {
            var trans = _feContainer.GetHorizontalOffset().Transform;
            trans.Animate(trans.X, _settingPanelWidth, TranslateTransform.XProperty, _slideDuration, 0, new CubicEase
            {
                EasingMode = EasingMode.EaseOut
            });

            _isSettingsOpen = true;
        }

        private void GestureListener_OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal)
            {
                double offset = _feContainer.GetHorizontalOffset().Value + e.HorizontalChange;
                if (offset < _settingPanelWidth && offset > 0)
                    _feContainer.SetHorizontalOffset(offset);
            }
        }

        private void GestureListener_OnDragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal)
            {
                if (e.HorizontalChange > _dragDistanceToOpen && !_isSettingsOpen)
                    OpenSettings();
                else if (e.HorizontalChange < _dragDistanceNegative && _isSettingsOpen)
                    CloseSettings();
                else
                    ResetLayoutRoot();
            }
        }

        private void SettingsStateGroup_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
        {
            ResetLayoutRoot();
        }

        private void ResetLayoutRoot()
        {
            if (!_isSettingsOpen)
                _feContainer.SetHorizontalOffset(0.0);
            else
                _feContainer.SetHorizontalOffset(_settingPanelWidth);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            if (_isSettingsOpen)
            {
                //Deployment.Current.Dispatcher.BeginInvoke(() =>
                //{
                CloseSettings();
                //});
            }
            else
            {
                ExitApp();
            }
            base.OnBackKeyPress(e);
        }

        #endregion

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            //if (Config.GetValue("tutorial1") == null)
            //{
            //    NavigationService.Navigate(new Uri("/Training.xaml", UriKind.Relative));
            //}
            if(Config.GetValue("1.0.0.1")==null){
                MessageBox.Show(@"Phiên bản 1.0.0.1:
- Đọc truyện theo kiểu cuộn hoặc lật trang.
- Ghim truyện yêu thích ra màn hình chính.","Có gì mới",MessageBoxButton.OK);
                Config.Init("1.0.0.1", "1",new DbContext());
            }
        }

        private void topbar_ExecuteSearch(object sender, EventArgs e)
        {
            if (topbar.SearchQuery.Length == 0) return;
            NavigationService.Navigate(new Uri(String.Format("/Search.xaml?keyword={0}", HttpUtility.UrlEncode(topbar.SearchQuery)), UriKind.Relative));
            topbar.SearchQuery = "";
        }

        private void MenuItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var menuItem = ((FrameworkElement)sender).DataContext as Models.MenuItem;
            if (menuItem.url == "Home")
            {
                if (_isSettingsOpen)
                    CloseSettings();
                return;
            }
            if (menuItem.url == "Setting")
            {
                NavigationService.Navigate(new Uri("/Setting.xaml",UriKind.Relative));
                return;
            }
            if(menuItem.url.StartsWith("/")){
                NavigationService.Navigate(new Uri(String.Format("/Genre.xaml?url={0}&title={1}", menuItem.url, HttpUtility.UrlEncode(menuItem.title)), UriKind.Relative));
            }
        }

        private void Navigate(UIElement form, string title)
        {
            Content.Children.Clear();
            Content.Children.Add(form);
            if (_isSettingsOpen)
                CloseSettings();

            topbar.Title = title;
        }

        private void topbar_MenuIconTap(object sender, EventArgs e)
        {
            if (!_isSettingsOpen)
            {
                OpenSettings();
            }
        }

        private void btnPower_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //Application.Current.Terminate();
            RateApp();
        }

        private static void RateApp()
        {
            int ratecount = Convert.ToInt32(Config.GetValue("ratecount"));
            if (ratecount != 1)
            {
                Config.SetValue("ratecount", (ratecount + 1).ToString());
                Application.Current.Terminate();
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {

                    CustomMessageBox messageBox = new CustomMessageBox()
                    {
                        Caption = String.Format("Đánh giá ứng dụng"),
                        Message = "Bạn thích ứng dụng này chứ. Xin hãy đánh giá 5* để giúp chúng tôi phát triển ứng dụng ngày càng tốt hơn ^_^",
                        LeftButtonContent = "đánh giá 5*",
                        RightButtonContent = "lần sau",
                    };

                    messageBox.Dismissed += (s1, e1) =>
                    {
                        switch (e1.Result)
                        {
                            case CustomMessageBoxResult.LeftButton:
                                API.RateApp();
                                Config.SetValue("ratecount", (ratecount + 1).ToString());
                                break;
                        }
                        Application.Current.Terminate();
                    };

                    messageBox.Show();
                });
            }
        }

        private static void ExitApp()
        {
            if (MessageBox.Show("Bạn muốn thoát ứng dụng?", "Thông báo", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                RateApp();
            }
        }

    }
}